<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
use User\Api\UserApi;
use Home\Model\UserModel ; 

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class UserController extends HomeController {

	public $user ; 
	public $uid = NULL ; 

	function _initialize(){
		parent::_initialize() ; 
		$this->user = new UserModel ; 
		if(is_login()){
			$this->uid = is_login();
			$info = $this->user->getUserInfoById($this->uid);
			$this->assign('info' , $info[0]) ; 
		}
		if(is_Login() && in_array(ACTION_NAME, array('login' , 'register'))){
			redirect(U('User/index'));
		}

	}
	/* 用户中心首页 */
	public function index(){
		if(!$this->uid){
			redirect(U('User/login'));
		}
		$this->display();
	}
	/**** 我的信息  ****/
	function info(){


		if(IS_POST){
			$post = I('post.');
			$user = array() ; 
			$user ['nickname'] = $post ['nickname'] ; 
			$user ['real_name'] = $post ['real_name'] ; 
			$user ['sex'] = $post ['sex'] == 1 ? 1 : 2 ;
			$user ['idcard'] = $post['idcard']; 
			$user ['id'] = $this->uid ; 
			$user ['birth'] = date( 'Y-m-d' ,strtotime($post ['year'] . '-' . $post ['month'] . '-' . $post ['day']) ); 
			$address = array();
			$address ['region1'] = $post ['region1'] ; 
			$address ['uid'] = $this->uid ; 
			$address ['region2'] = $post ['region2'] ; 
			$address ['detail'] = $post ['detail'] ;

			if(mb_strlen($user['nickname']) > 6 || mb_strlen($user['nickname'])  < 1 ){
				$this->error('昵称在1-6个之间');
			}
			if( mb_strlen($user ['real_name']) > 6 ||  mb_strlen($user ['real_name']) < 1  ){
				$this->error('请输入正确的真实姓名');
			}
			if(!preg_match('/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/', $user['idcard'])){
				$this->error("身份证号码不正确");
			}
			$flag = M('UcenterMember')->save($user); 
			$addressid = $post ['addressid'] ; 
			if(!$addressid){
				$flag = M('Address')->add($address);
			}else{
				$res = M('Address')->where(array('id' => $addressid))->find();
				if($res){
					$flag = M('Address')->where(array('id' => $addressid))->save($address);
				}
			}
			$this->success('更新资料成功');
		}
		$this->display();
	}



	/* 注册页面 */
	public function register($username = '', $password = '', $repassword = '', $code = '' , $email = ''){
        if(!C('USER_ALLOW_REGISTER')){
            $this->error('注册已关闭');
        }

		if(IS_POST){ //注册用户
			/* 检测密码 */
			if($password != $repassword){
				$this->error('密码和重复密码不一致！');
			}
			$preg = '/^1[3|4|7|5|6|8|9]\d{9}$/';
			if(!preg_match($preg, $username)){
				$this->error('手机号码格式不正确');
			}
			$preg = '/^[0-9a-zA-Z_,\.\*\!&]{6,15}$/';
			if(!preg_match($preg, $password)){
				$this->error('密码长度为6-16位，只能含有.*!&等特殊字符');
			}
			$sms_code = session('user_register');
			if(!$sms_code){
				$this->error('短信验证码不正确');
			}
			if($username != $sms_code['mobile'] || $code != $sms_code['code']){
				$this->error('验证码不正确');
			}
			/* 调用注册接口注册用户 */
            $User = new UserApi;
            $email = $username . '@qq.com';
			$uid = $User->register($username, $password, $email);
			if(0 < $uid){
				$refer =  get_redirect_url(U('User/login'));
				$arr = array(
					'status' => 1 ,
					'url' => $refer 
					);
				exit(json_encode($arr));
			} else { //注册失败，显示错误信息
				$this->error($this->showRegError($uid));
			}

		} else { //显示注册表单
			$this->display();
		}
	}

	/* 登录页面 */
	public function login($username = '', $password = '', $verify = '' , $rememberme = 0 ){
		if(IS_POST){ //登录验证
			/* 检测验证码 */
			// if(!check_verify($verify)){
			// 	$this->error('验证码输入错误！');
			// }

			/* 调用UC登录接口登录 */
			$user = new UserApi;
			$uid = $user->login($username, $password);
			if(0 < $uid){ //UC登录成功
				/* 登录用户 */ 
				$Member = D('Member');
				if($Member->login($uid , $rememberme)){ //登录用户
					$refer = get_redirect_url(U('User/index'));
					$arr = array(
						'status' => 1 ,
						'url' => $refer 
						);
					exit(json_encode($arr));
				} else {
					$this->error($Member->getError());
				}

			} else { //登录失败
				switch($uid) {
					case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
					case -2: $error = '密码错误！'; break;
					default: $error = '未知错误！'; break; // 0-接口参数错误（调试阶段使用）
				}
				$this->error($error);
			}

		} else { //显示登录表单
			$this->display();
		}
	}

	/* 退出登录 */
	public function logout(){
		if(is_login()){
			D('Member')->logout();
			$this->success('退出成功！', U('User/login'));
		} else {
			$this->redirect('User/login');
		}
	}

	/* 验证码，用于登录和注册 */
	public function verify(){
		$verify = new \Think\Verify();
		$verify->entry(1);
	}

	/**
	 * 获取用户注册错误信息
	 * @param  integer $code 错误编码
	 * @return string        错误信息
	 */
	private function showRegError($code = 0){
		switch ($code) {
			case -1:  $error = '用户名长度必须在16个字符以内！'; break;
			case -2:  $error = '用户名被禁止注册！'; break;
			case -3:  $error = '用户名被占用！'; break;
			case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
			case -5:  $error = '邮箱格式不正确！'; break;
			case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
			case -7:  $error = '邮箱被禁止注册！'; break;
			case -8:  $error = '邮箱被占用！'; break;
			case -9:  $error = '手机格式不正确！'; break;
			case -10: $error = '手机被禁止注册！'; break;
			case -11: $error = '手机号被占用！'; break;
			default:  $error = '未知错误';
		}
		return $error;
	}


    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function profile(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',U('User/login') );
		}
        if ( IS_POST ) {
            //获取参数
            $uid        =   is_login();
            $password   =   I('post.old');
            $repassword = I('post.repassword');
            $data['password'] = I('post.password');
            empty($password) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($repassword) && $this->error('请输入确认密码');

            if($data['password'] !== $repassword){
                $this->error('您输入的新密码与确认密码不一致');
            }

            $Api = new UserApi();
            $res = $Api->updateInfo($uid, $password, $data);
            if($res['status']){
                $this->success('修改密码成功！');
            }else{
                $this->error($res['info']);
            }
        }else{
            $this->display();
        }
    }

}
